package utl.mofen.jsonStreamHandler;

import java.io.File;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import utl.mofen.jsonStreamHandler.IJSonStreamHandler;
import utl.mofen.objects.JSonStream;
import utl.mofen.utils.FileUtil;
import utl.mofen.utils.StringUtil;

import com.google.gson.JsonElement;

public class HandlerFactory {
	private static ApplicationContext ctx = null;
	private static final Logger logger = Logger.getLogger(HandlerFactory.class);
	
	public static void checkInitialize(String file)
	{
		if (StringUtil.stringIsEmpty(file))
		{	
			file = FileUtil.getRootPath() + "Handler.xml";
		}		
		if (ctx==null)
		{
			System.out.println("载入HandlerFactory配置文件:" + file);
			ctx = new FileSystemXmlApplicationContext(file);
		}
	}
	
	public static IJSonStreamHandler createHandler(JSonStream jsonStreamObject) throws Exception
	{
		if (ctx==null)
		{
			throw new Exception("先调用checkInitialize进行初始化");
		}
	
		JsonElement e = jsonStreamObject.getJSonObject().get("plugin");
		if (e==null)
		{
			throw new Exception("没有配置plugin");
		}
		
		if (e.getAsJsonObject().get("name")==null)
		{
			throw new Exception("没有配置知道要执行的插件名称(plugin.name)");			
		}
		
		String pluginName = e.getAsJsonObject().get("name").getAsString();		
		return createHandler(pluginName);
	}
	
	public static IJSonStreamHandler createHandler(String pluginName) throws Exception
	{	
		if (ctx==null)
		{
			throw new Exception("先调用checkInitialize进行初始化");
		}
		
		if (StringUtil.stringIsEmpty(pluginName))
		{
			throw new Exception("没有配置知道要执行的插件名称");			
		}
   		logger.info("创建了插件" + pluginName);
		return (IJSonStreamHandler)ctx.getBean(pluginName);
	}
}
